#include "HashTable.h"

HashNode::HashNode (int key, Trapeze& figure)
{
	this->key = key;
	this->figure = figure;
	this->nextPtr = nullptr;
}

Trapeze& HashNode::getFigure()	{return figure;}

int HashNode::getKey()	{return key;}

HashTable::HashTable(void)
{
	table = new HashNode*[DEFAULT_HASHTABLE_SIZE];
	for (int i = 0; i < DEFAULT_HASHTABLE_SIZE; i++)
		table[i] = nullptr;
}

HashTable::~HashTable(void)
{
	for (int i = 0; i < DEFAULT_HASHTABLE_SIZE; i++)
		if (table[i] != nullptr)
			delete table[i];
	delete[] table;
}

int HashTable::HashFunction(Trapeze& figure)
{
	POINT points[N];
	figure.getPoints(points);
	int hashValue = figure.getFloodColor() + figure.getLineColor();
	for (int i = 0; i < N; i++)
		hashValue += points[i].x + points[i].y;
	hashValue = hashValue %DEFAULT_HASHTABLE_SIZE;	// Modular Hash Function
	return hashValue;
}

void HashTable::Add (Trapeze& figure)
{
	int hashValue = HashFunction(figure);
	if (table[hashValue] != nullptr)
		table[hashValue] = new HashNode(hashValue, figure);
	else
	{
		HashNode* ptr = table[hashValue]->nextPtr;
		while (ptr != nullptr)
			ptr = ptr->nextPtr;
		ptr = new HashNode(hashValue, figure);
	}
}

bool HashTable::Remove(int key)
{
	if (table[key] != nullptr && table[key]->nextPtr == nullptr)
	{
		HashNode* ptr = table[key];
		table[key] = nullptr;
		delete ptr;
		return true;
	}
	else
		return false;
}

bool HashTable::Remove(Trapeze& figure) { return Remove(HashFunction(figure));}

bool HashTable::Compare(Trapeze& firstFigure, Trapeze& secondFigure)
{
	if (
		firstFigure.getFloodColor() == secondFigure.getFloodColor() &&
		firstFigure.getLineColor()  == secondFigure.getLineColor()
		)
	{
		POINT firstPoints[N];
		POINT secondPoints[N];
		if (firstPoints == secondPoints)
			return true;
		else
			return false;
	}
	else
		return false;
}
int HashTable::Search(Trapeze& figure)
{
	int hashValue = HashFunction(figure);
	HashNode* ptr = table[hashValue]->nextPtr;
	if (table[hashValue] != nullptr)
		do 
		{
			if (Compare(figure, table[hashValue]->figure))
				return hashValue;
			ptr = ptr->nextPtr;
		} 
		while (ptr != nullptr);
	return -1;
}